<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    :title="getTitle"
    @ok="handleOK"
  >
    <BasicForm @register="registerForm" v-if="activeKeyHeader === '1' || activeKeyHeader === '0'">
      <template #personalLetter>
        <!-- //私信 -->
        <div v-for="(comment, index) in chats" :key="index" style="margin: 0px 0 20px 0">
          <div style="display: flex; align-items: center">
            <a-input
              v-model:value="comment.content"
              style="width: 500px"
              placeholder="请输入私信内容"
            />
            <Icon
              icon="ant-design:plus-circle-outlined"
              @click="addChats"
              :size="30"
              v-if="index == 0"
              style="margin-left: 5px"
            />
            <Icon
              icon="ant-design:close-circle-outlined"
              @click="delChats(index)"
              :size="30"
              v-if="index != 0"
              style="margin-left: 5px"
            />

            <a-button style="margin: 0 5px" @click="openImageSelector(index, 'chat')"
              >选择图片</a-button
            >
            <div>
              <span v-for="(image, imgIndex) in comment.photos" :key="imgIndex">
                <img :src="image" style="width: 50px; height: 50px; margin-left: 10px" />
              </span>
            </div>
          </div>
        </div>
      </template>
    </BasicForm>
    <div style="margin-left: 20px">
      <Card
        v-if="activeKeyHeader === '1' || activeKeyHeader === '0'"
        :tab-list="tabListTitle"
        v-bind="$attrs"
        :active-tab-key="activeKey"
        @tab-change="onTabChange"
      >
        <div>
          <Textarea
            v-if="activeKey == '0'"
            v-model:value="formattedLinks"
            :placeholder="t('sys.configuration.inputViecottext')"
            :rows="10"
          />
          <BasicTable v-else @register="registerTableUrl">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction
                  :actions="[
                    {
                      label: t('sys.script.details'),
                      tooltip: t('sys.script.details'),
                      onClick: handleView.bind(null, record),
                    },
                  ]"
                />
              </template>
            </template>
          </BasicTable>
        </div>
      </Card>
    </div>

    <!-- 图库 -->
    <!-- <div>
      <div v-if="activeKeyHeader === '2'">
        <Upload
          action="http://8.136.118.105:8008/file/uploadImage"
          list-type="picture-card"
          v-model:file-list="fileList"
          @change="handleUploadChange"
        >
          <div v-if="fileList.length < 8">
            <plus-outlined />
            <div class="ant-upload-text">图片上传</div>
          </div>
        </Upload>
      </div>
      <a-modal :visible="previewVisible" :footer="null">
        <img style="width: 100%" :src="previewImage" />
      </a-modal>
    </div> -->

    <Modal v-model:visible="imgvisible" style="top: 400px" title="图片选择" @ok="handleOkimg">
      <CheckboxGroup v-model:value="selectedImagesA">
        <div v-for="(image, index) in selectedImages" :key="index">
          <Checkbox :value="image">
            <img :src="image" style="width: 100px; height: 100px" />
          </Checkbox>
        </div>
      </CheckboxGroup>
    </Modal>
    <!-- <DetailView @register="registerDetailView" @success="DetailViewSuccess"> </DetailView> -->
  </BasicModal>
</template>

<script lang="ts" setup>
  import { useModal } from '@/components/Modal';
  // import DetailView from './DetailView.vue';
  import Icon from '@/components/Icon/Icon.vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getTaskDetailApi } from '@/api/demo/Task';
  import {
    Card,
    Textarea,
    Modal,
    CheckboxGroup,
    Checkbox,
    Upload,
    FormItem,
    Tooltip,
    Progress,
  } from 'ant-design-vue';
  import { ref, computed, unref, h } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { accountFormSchema } from './account.data';
  import { getTasklistAPI } from '@/api/demo/InformationMatching';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  defineOptions({ name: 'AccountModal' });
  // 变量定义
  const activeKey = ref('0');
  const activeKeyHeader = ref('0');
  const previewVisible = ref<boolean>(false);
  const previewImage = ref<string | undefined>('');
  const fileList = ref([]);
  const selectedImagesA = ref([]);
  const selectedImages = ref([]);
  const Data = ref<any>({}); // 定义 Data 为响应式变量
  const chats = ref([
    {
      content: '',
      photos: [],
    },
  ]);
  const comments = ref([
    {
      content: '',
      photos: [],
    },
  ]);
  const tabListTitle = [
    {
      key: '0',
      tab: '手动录入',
    },
    {
      key: '1',
      tab: '筛选',
    },
  ];
  const tabListTitleHeader = [
    {
      key: '0',
      tab:  t('sys.audienceGroup.mac'),
    },
    {
      key: '1',
      tab: t('sys.comment.columns.comment'),
    },
    {
      key: '2',
      tab: '图库',
    },
  ];
  const formattedLinks = computed({
    get() {
      return links.value.join(',\n'); // 将数组转换为带逗号和换行符的字符串
    },
    set(value) {
      links.value = value.split(',\n'); // 将带逗号和换行符的字符串转换为数组
    },
  });
  const links = ref<string[]>([]); // 将 links 定义为字符串数组
  const formValue = ref({
    maxNum: '',
    keyWord: '',
    timestamp: '',
  });
  const imgvisible = ref(false);
  const isUpdate = ref(true);
  const rowId = ref('');
  const modalWidth = ref('50%');
  const emit = defineEmits(['success']);
  const total = ref(0);
  const [registerDetailView, { openModal: openDetailView }] = useModal();
  // 方法定义
  const [
    registerForm,
    {
      resetFields,
      setFieldsValue,
      updateSchema,
      getFieldsValue,
      appendSchemaByField,
      removeSchemaByField,
      validate,
    },
  ] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  });
  const columnsModelstab = ref([
    {
      title: t('sys.informaionMatchaing.columns.title'),
      dataIndex: 'title',
      width: 120,
    },
    {
      title: t('sys.configuration.describe'),
      dataIndex: 'remark',
      width: 120,
      customRender: ({ text }: { text: string }) => {
        return h(
          Tooltip,
          {
            title: text,
          },
          [
            h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%',
                  height: 'auto',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                },
              },
              text,
            ),
          ],
        );
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.status'),
      dataIndex: 'status',
      width: 120,
      customRender: ({ record }: { record: Recordable }) => {
        if (record.status === t('sys.configuration.inProgress')) {
          if (record.status1 !== t('sys.configuration.taskSucces')) {
            return `一阶段状态 ${record.status1}`;
          } else {
            return `二阶段状态 ${record.status2}`;
          }
        }
        return record.status;
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.type'),
      dataIndex: 'type',
      width: 80,
      customRender: ({ record }: { record: Recordable }) => {
        return record.type == 'orientation' ? t('sys.informaionMatchaing.columns.orientation') : t('sys.informaionMatchaing.columns.match');
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.currentNode'),
      dataIndex: 'currentNode',
      width: 80,
      customRender: ({ record }: { record: Recordable }) => {
        const currentNode = record.currentNode ?? '-';
        const maxNode = record.maxNode ?? '-';
        return `${currentNode}/${maxNode}`;
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.success'),
      dataIndex: 'success',
      width: 80,
      customRender: ({ record }: { record: Recordable }) => {
        const success = record.success ?? '-';
        const maxNum = record.maxNum ?? '-';
        return `${success}/${maxNum}`;
      },
    },
  ]);
  const [registerTableUrl] = useTable({
    api: async (params) => {
      const result = (await getTasklistAPI(params)) as { items: any[]; total: number };
      total.value = result.total;
      return result;
    },
    rowKey: 'id',
    columns: columnsModelstab,
    actionColumn: {
      width: 80,
      title: t('sys.configuration.action'),
      dataIndex: 'action',
    },
    scroll: {
      y: 300, // 设置表格的最小高度为 300px
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      getDetail(data.record.id);
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
    const handleCancel = () => {
      previewVisible.value = false;
    };

    // const treeData = await getDeptList();
    // updateSchema([
    //   {
    //     field: 'pwd',
    //     show: !unref(isUpdate),
    //   },
    //   {
    //     field: 'dept',
    //     componentProps: { treeData },
    //   },
    // ]);
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('sys.configuration.add') : t('sys.configuration.edit')));

  async function handleOK() {
    const commentsWithPhotosString = comments.value.map((comment) => ({
      ...comment,
      photos: comment.photos.join(','),
    }));

    const chatsWithPhotosString = chats.value.map((chat) => ({
      ...chat,
      photos: chat.photos.join(','),
    }));

    const linksArray = Array.isArray(links.value) ? links.value : links.value.split(',');

    const Data = {
      ...getFieldsValue(),
      comments: commentsWithPhotosString,
      chats: chatsWithPhotosString,
      photos: selectedImages.value,
      links: linksArray,
    };
    try {
      let data;
      if (isUpdate.value) {
        // 调用编辑接口
        let params = {
          id: rowId.value,
          ...Data,
        };
        data = await updateTaskApi(params);
      } else {
        // 调用新增接口
        data = await createTaskApi(Data);
      }
      emit('success', data);
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function onTabChange(key) {
    activeKey.value = key;
  }

  function onTabChangeHeader(key) {
    activeKeyHeader.value = key;
    //私信/评论展示哪个
    if (key == 0) {
      updateSchema([
        {
          field: 'chatNum',
          ifShow: true,
        },
        {
          field: 'chatRule',
          ifShow: true,
        },
        {
          field: 'commentRule',
          ifShow: false,
        },
        {
          field: 'commentNum',
          ifShow: false,
        },
      ]);
    } else {
      updateSchema([
        {
          field: 'commentRule',
          ifShow: true,
        },
        {
          field: 'commentNum',
          ifShow: true,
        },
        {
          field: 'chatNum',
          ifShow: false,
        },
        {
          field: 'chatRule',
          ifShow: false,
        },
      ]);
    }
  }

  function add() {
    comments.value.push({ content: '', photos: [] });
  }

  function del(index: number) {
    comments.value.splice(index, 1);
  }

  function addChats() {
    chats.value.push({ content: '', photos: [] });
  }

  function delChats(index: number) {
    chats.value.splice(index, 1);
  }

  function openImageSelector(index: number, type: 'comment' | 'chat') {
    currentIndex.value = index;
    currentType.value = type;
    imgvisible.value = true;
  }

  const currentIndex = ref(-1);
  const currentType = ref<'comment' | 'chat'>('comment');

  function handleOkimg() {
    if (currentIndex.value !== -1) {
      if (currentType.value === 'comment') {
        comments.value[currentIndex.value].photos = selectedImagesA.value;
      } else if (currentType.value === 'chat') {
        chats.value[currentIndex.value].photos = selectedImagesA.value;
      }
    }
    imgvisible.value = false;
    selectedImagesA.value = [];
  }

  function handleUploadChange(info) {
    if (info.file.status === 'done') {
      const response = info.file.response;
      if (response) {
        selectedImages.value.push(response);
      }
    }
  }

  function handleView(record: Recordable) {
    openDetailView(true, {
      record,
    });
  }

  async function getDetail(id) {
    if (id) {
      let Data = await getTaskDetailApi(id);
      if (Data.data.chats) {
        Data.data.chats.forEach((chat) => {
          chat.photos = chat.photos ? chat.photos.split(',') : [];
        });
      }
      if (Data.data.comments) {
        Data.data.comments.forEach((comment) => {
          comment.photos = comment.photos ? comment.photos.split(',') : [];
        });
      }
      if (Data.data.photos) {
        selectedImages.value = Data.data.photos;
        fileList.value = Data.data.photos.map((photoUrl) => ({
          uid: photoUrl, // 假设每个图片 URL 是唯一的标识符
          name: 'image.png', // 可以根据需要设置图片名称
          status: 'done', // 设置图片上传状态为已完成
          url: photoUrl, // 图片 URL
        }));
      }
      chats.value = Data.data.chats;
      comments.value = Data.data.comments;
    }
  }

  function DetailViewSuccess(record: Recordable) {
    links.value = record.urls;
  }
</script>
